﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Bootstrap.Security.Authentication
{
    /// <summary>
    /// BootstrapAdmin JWT 授权操作类
    /// </summary>
    public static class BootstrapAdminJwtTokenHandler
    {
        /// <summary>
        /// 通过指定用户名创建 JWT Token
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="configure">Token 配置信息</param>
        /// <returns>Json Web Token (JWT)</returns>
        public static string CreateToken(string userName, Action<TokenValidateOption> configure = null)
        {
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, userName));
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenOption = new TokenValidateOption();
            configure?.Invoke(tokenOption);
            return tokenHandler.CreateEncodedJwt(new SecurityTokenDescriptor()
            {
                Issuer = tokenOption.Issuer,
                Audience = tokenOption.Audience,
                Subject = identity,
                Expires = DateTime.Now.AddMinutes(tokenOption.Expires),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOption.SecurityKey)), SecurityAlgorithms.HmacSha256)
            });
        }
    }
}
